#encoding:utf-8

from django.db import models
from tinymce.models import HTMLField
from django.core.exceptions import ObjectDoesNotExist
from django.utils import timezone,tzinfo
from szdb.adjtime import timeFormat
import traceback

## 数据库异常类
#
#class Error(Exception):
#    pass
#
#    
##class DBException(Error):
##    def __int__(self, value):
##        self.value = value
#
#    
#    
#class DataException(Error):
#    def __int__(self, value):
#        self.value = '%s: data not correctly format' % value


# 新闻栏目

class NewsType(models.Model):
    
    
    class Meta:
        verbose_name = '栏目'
        verbose_name_plural = '栏目管理'
    title = models.CharField(max_length=50, verbose_name='标题')

    def __unicode__(self):
        return u'%s' % self.title

# 新闻

class News(models.Model):
    
    
    class Meta:
        verbose_name = '新闻'
        verbose_name_plural = "我的新闻管理"

    keyword = models.CharField(max_length=500, verbose_name='关键字')
    title = models.CharField(max_length=50, verbose_name='标题')
    type = models.ForeignKey(NewsType, verbose_name='栏目')
    releasetime = models.DateTimeField(verbose_name='发布时间')
    content = HTMLField(verbose_name='内容')

    def __unicode__(self):
        return u'%s,类型：%s,关键字:%s,建立于%s' % (self.title, self.type, self.keyword, self.releasetime)

    # 返回时间节点之后的所有新闻
    """
    ztj 2012-8-24 修改，直接返回空集合
    """
    def retrieve_news(self, data):
#        return True
        typeid = data['typeid']
        lasttime = data['lasttime']
        #print lasttime
        return_news = News.objects.filter(type_id=typeid).filter(releasetime__gte=lasttime)
        print type(return_news)
        print len(return_news)
        newslist = []
#        if len(return_news) > 0:
        return return_news
#        else:
#            return False
        
        



# 用户模块

class User(models.Model):

    class Meta:
        verbose_name = '手机端注册用户'
        verbose_name_plural = '手机端注册用户管理'

    # 可以使用中文，但禁止除[@][.]以外的特殊符号
    username = models.CharField(max_length=100, verbose_name='用户名', unique=True,primary_key=True)
    # 使用md5进行加密
    password = models.CharField(max_length=100, verbose_name='密码')
    # 系统管理员0 普通用户1
    TYPE_CHOICES = ((0, '系统管理员'), (1, '普通用户'))
    type = models.IntegerField(verbose_name='用户类型', choices=TYPE_CHOICES)
    email = models.EmailField(verbose_name='注册邮箱', unique=True)
    safequestion = models.CharField(max_length=100, verbose_name='安全问题')
    safeanswer = models.CharField(max_length=100, verbose_name='问题答案')
    SEX_CHOICES = (('0', '保密') , ('1', '女') , ('2', '男'))
    sex = models.CharField(max_length=5 , choices=SEX_CHOICES, verbose_name='性别')
    
    def __unicode__(self):
        return u'%s' % self.username
    
    # 返回用户名是否可用
    def is_username_unique(self, data):
        try:
            User.objects.get(username=data['username'])
        except ObjectDoesNotExist:
            return True
        return False
    
    # 返回邮箱是否可用
    def is_email_unique(self, data):
        try:
            User.objects.get(email=data['email'])
        except ObjectDoesNotExist:
            return True
        return False

    # 注册
    """
    ztj 2012-8-24 修改
    """
    def register(self, data):
        flag = True
        try:
            new_user = User()
            new_user.username = data['username']
            new_user.password = data['password']
            new_user.email = data['email']
            new_user.safequestion = data['safequestion']
            new_user.safeanswer = data['safeanswer']
            new_user.sex = data['sex']
            if(data['username'] == '' or data['password'] == '' 
                or data['email'] == '' or data['safequestion'] == ''
                or data['safeanswer'] == ''or data['sex'] == ''):
                flag = False;
                return False
            new_user.type = 1;
            if (self.is_username_unique({'username':new_user.username}) and self.is_email_unique({'email':new_user.email})): 
                new_user.save()
            else:
                print('username or email is already exist!')
                flag = False # 需要返回错误信息
                return False
        except Exception, e:
            raise e
        finally:
            return [new_user.username, new_user.pk, flag]
    
    # 登录
    def login(self, data):
        try:
            username = data['username']
            password = data['password']
            #返回为空的情况
            user = User.objects.get(username=username)
            if user.password == password:
                return [user.username, user.pk, True]
            else:
                return False
        except ObjectDoesNotExist,e:
            raise e
            print('The user is not exist')
            return False
        except Exception ,e:
            raise e
            return False
        
    # 返回注册安全问题
    def get_safequestion(self, data):
        try:
            user = User.objects.get(username=data['username'])
            return user.safequestion
        except ObjectDoesNotExist:
            print('The user is not exist')
            return False
    
    #####################################    
    # 验证安全问题答案,如果正确就修改注册用户密码
    ##########################################
    def is_answer_right(self, data):
        '''
        arg : data {username,safequestion,safeanswer,newpassword}
        '''
        try:
            username = data['username']
            safeanswer = data['safeanswer']
            safequestion = data['safequestion']
            newpassword = data['newpassword']
            user = User.objects.get(username=username)
            if user.safequestion == safequestion and user.safeanswer == safeanswer:
                user.password = newpassword
                user.save()
                return True
            else:
                return False
        except ObjectDoesNotExist:
            print('The user is not exist')
            return False
    
    # 密码重设
    # 需要先输入旧的密码
    """
    ztj 2012-8-24 需要输入新旧密码
    """
    def reset_key(self, data):
        try:
            username = data['username']
            password = data['password']
            newpsw = data['newpsw']
            user = User.objects.get(username=username)
            if user.password == password:
                user.password = newpsw
                user.save()
                return True
            else:
                return False
        except ObjectDoesNotExist:
            print('The user is not exist')
            traceback.print_exc()
            return False
    
    # 参加活动

    def attend_activity(self, data):
        try:
            username = data['username']
            activityid = data['activityid']
            user = User.objects.get(username=username)
            activity = Activity.objects.get(pk=activityid)
            activity.userlist.add(user)
            activity.save()
            return True
        except:
            return False    
        
        

# 活动类

class Activity(models.Model):
    
    
    class Meta:
        verbose_name = '活动'
        verbose_name_plural = "活动管理"
    
    title = models.CharField(max_length= 50, verbose_name= '活动名称')
    content = models.TextField(verbose_name= '活动介绍')
    # 建立活动时自动添加当前时间为发布时间
    releasetime = models.DateTimeField(auto_now_add= True, verbose_name= '发布时间')
    # 用datetime类型来储存
    date = models.DateTimeField(verbose_name= '活动时间')
    owner = models.ForeignKey(User, verbose_name='发起用户', related_name='o+')
    userlist = models.ManyToManyField(User, verbose_name='参与用户列表', related_name='u+', blank=True)
    place = models.CharField(max_length=50, verbose_name='地点')
    
    def __unicode__(self):
        return u'%s,发布时间：%s,活动时间:%s,内容:%s' % (self.title, self.releasetime, self.date, self.content)

    # 返回时间节点之后的所有活动
    """
    ztj 2012-8-24 修改，直接返回空集合
    """
    def retrieve_activity(self, data):
        lasttime = data['lasttime']
        return_activity = Activity.objects.filter(releasetime__gte=lasttime)
#        if len(return_activity) > 0:
#            activityList = []
#            for single_activity in return_activity:
#                
        return return_activity
#        else:
#            return False
        
    # 增加活动
    def add_activity(self, data):
        result = True
        try:
            new_acti = Activity()
            new_acti.title = data['title']
            new_acti.owner = User.objects.get(pk=data['uid'])
            new_acti.date = data['date'] #需要转化为时间戳
            new_acti.content = data['content']
            new_acti.place = data['place']
            new_acti.save()
            result = new_acti.pk
        except Exception,e :
            traceback.print_exc()
            result = False
        finally:
            return result

    # 根据id查询活动的详细信息
    def get_activity_detail(self, data):
        new_acti = Activity.objects.get(pk = data['id']);
        return new_acti.userlist.all()

